<template>
    <div>
        <div ref="draginput" class="sel-box"
          :class="isActive ? 'active-border' : 'inactive-border'">
          <input type="file" ref="fileInput"
            accept="text/csv" hidden @change="onFileChange">
          <el-button type="primary" size="small" @click="onButtonClick">拖动或选择文件</el-button>
          <span>{{showText}}</span>
        </div>
    </div>
</template>

<script>
import tools from '../utils/tools';

const regPureNumber = /^[0-9]+$/i;
const regComma = /["]+/g;

export default {
  data() {
    return {
      isActive: false,
      showText: '点击按钮或者拖动csv文件到这里',
    };
  },

  mounted() {
    const that = this;

    this.$refs.draginput.ondragover = (e) => {
      e.preventDefault();
    };

    this.$refs.draginput.ondragenter = (e) => {
      e.preventDefault();
      that.isActive = true;
    };

    this.$refs.draginput.ondragleave = (e) => {
      e.preventDefault();
      that.isActive = false;
    };

    this.$refs.draginput.ondrop = (e) => {
      e.preventDefault();
      e.stopPropagation();

      that.isActive = false;

      const { files } = e.dataTransfer;
      if (files.length < 1) {
        that.showText = '请拖动csv文件到这里';
        that.$emit('filechange', {
          valid: false,
        });
      } else {
        const file = files[0];
        if (file.name.endsWith('.csv') || file.name.endsWith('.CSV')) {
          that.showText = file.name;
          that.parseCSV(file);
        } else {
          that.invalidFile('不是csv文件');
        }
      }
    };
  },

  methods: {
    onButtonClick() {
      this.$refs.fileInput.click();
    },
    onFileChange() {
      const f = this.$refs.fileInput.files[0];
      this.showText = f.name;
      this.parseCSV(f);
    },
    parseCSV(csvFile) {
      const that = this;

      const reader = new FileReader();
      reader.onload = (event) => {
        const loading = that.$loading({
          lock: true,
          text: '文件读取中',
          spinner: 'el-icon-loading',
          background: 'rgba(68, 68, 68, 0.7)',
        });

        const text = event.target.result;
        const lines = text.trim().split('\n').flatMap(l => [l.trim().split(',')]);
        if (lines.length >= 8 && lines[0].length === 1 && (lines[0][0].endsWith('.csv') || lines[0][0].endsWith('.CSV'))) {
          that.parsePCFile(lines);
        } else if (lines.length >= 2 && lines[0].length > 2 && lines[0][0].startsWith('Record')) {
          that.parseUSBFile(lines);
        } else {
          that.invalidFile('无效的csv文件');
        }

        setTimeout(() => {
          loading.close();
        }, 100);
      };
      reader.readAsText(csvFile);
    },
    invalidFile(msg) {
      this.showText = msg;
      this.$emit('filechange', {
        valid: false,
      });
    },
    parsePCFile(lines) {
      const chIndex = [];
      const channels = [];

      lines[5].forEach((item, index) => {
        const t = item.replace(regComma, '').trim();
        if (regPureNumber.test(t)) {
          chIndex.push(index);
          channels.push({
            title: t,
            unit: lines[4][index].replace(regComma, '').trim(),
            data: [],
          });
        }
      });

      lines.slice(7).forEach((l, lineIndex) => {
        chIndex.forEach((chI, index) => {
          try {
            channels[index].data.push(tools.toNumber(l[chI]));
          } catch (e) {
            channels[index].data.push(0);
            console.error(`the ${index + 1} value of line ${lineIndex + 8} is ${l[chI]} -> ${e.message}`);
          }
        });
      });

      this.$emit('filechange', {
        valid: true,
        channels,
        baseIndex: 8,
      });
    },
    parseUSBFile(lines) {
      const chIndex = [];
      const channels = [];

      lines[0].forEach((item, index) => {
        const t = item.replace(regComma, '').trim();
        if (t.startsWith('Ch')) {
          const leftIndex = t.indexOf('(');
          chIndex.push(index);
          channels.push({
            title: t.substring(0, leftIndex).trim(),
            unit: t.substring(leftIndex + 1, t.length - 1).trim(),
            data: [],
          });
        }
      });

      lines.slice(1).forEach((l, lineIndex) => {
        chIndex.forEach((chI, index) => {
          try {
            channels[index].data.push(tools.toNumber(l[chI]));
          } catch (e) {
            channels[index].data.push(0);
            console.error(`the ${index + 1} value of line ${lineIndex + 8} is ${l[chI]} -> ${e.message}`);
          }
        });
      });

      this.$emit('filechange', {
        valid: true,
        channels,
        baseIndex: 1,
      });
    },
  },
};
</script>


<style scoped>
.sel-box {
  width: 100%;
  height: 80px;

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}

.active-border {
  border: 2px dashed red
}

.inactive-border {
  border: 2px dashed gray
}
</style>
